package com.ssjhs.installservice;

import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class UdpServer extends Thread {
    private final String TAG = "UdpServer";

    private static final int PORT = 4040;

    public UdpServer() {
        start();
    }

    public void release() {
        interrupt();
    }

    @Override
    public void run() {
        try {
            DatagramSocket socket = new DatagramSocket(PORT);
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            byte[] recvPacket = new byte[100];
            DatagramPacket packet = new DatagramPacket(recvPacket, recvPacket.length, inetAddress, PORT);
            boolean isRunning = true;
            while (isRunning) {
                socket.receive(packet);
                String packetName = new String(recvPacket, 0, packet.getLength());
                restartApp(packetName);
            }
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

    private void restartApp(String packageName) {
        stopApp(packageName);
        startApp(packageName);
    }

    private static void startApp(String packageName) {
        String command;
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        try {
            // 申请su权限
            Process process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());

            // 执行命令
            command = "am start " + packageName + "/.MainActivity" + "\n";
            dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
            dataOutputStream.flush();
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String msg = "";
            String line;
            // 读取命令的执行结果
            while ((line = errorStream.readLine()) != null) {
                msg += line;
            }
            Log.e("TAG", "adb shell msg is " + msg);
//            // 如果执行结果中包含Failure字样就认为是安装失败，否则就认为安装成功
//            if (!msg.contains("Failure")) {
//
//            }
        } catch (Exception e) {
            Log.e("TAG", e.getMessage(), e);
        } finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
            } catch (IOException e) {
                Log.e("TAG", e.getMessage(), e);
            }
        }
    }

    private static void stopApp(String packageName) {
        String command;
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        try {
            // 申请su权限
            Process process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());

            // 执行命令
            command = "am force-stop " + packageName + "\n";
            dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
            dataOutputStream.flush();
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String msg = "";
            String line;
            // 读取命令的执行结果
            while ((line = errorStream.readLine()) != null) {
                msg += line;
            }
            Log.e("TAG", "adb shell msg is " + msg);
//            // 如果执行结果中包含Failure字样就认为是安装失败，否则就认为安装成功
//            if (!msg.contains("Failure")) {
//
//            }
        } catch (Exception e) {
            Log.e("TAG", e.getMessage(), e);
        } finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
            } catch (IOException e) {
                Log.e("TAG", e.getMessage(), e);
            }
        }
    }

}
